<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <div class="flex items-center">
        <button @click="$router.back()" class="mr-4 p-2 text-gray-500 hover:text-gray-700 focus:outline-none">
          <ArrowLeftIcon class="h-6 w-6" />
        </button>
        <h2 class="text-2xl font-semibold text-gray-800">申请详情</h2>
      </div>
      <div class="flex space-x-3">
        <button @click="editApplication" v-if="application && application.status === 'PENDING'" class="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
          <PencilIcon class="h-5 w-5 mr-2" />
          编辑申请
        </button>
        <button @click="approveApplication" v-if="application && application.status === 'PENDING' && hasApprovalPermission()" class="flex items-center px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2">
          <CheckIcon class="h-5 w-5 mr-2" />
          批准申请
        </button>
        <button @click="rejectApplication" v-if="application && application.status === 'PENDING' && hasApprovalPermission()" class="flex items-center px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2">
          <XMarkIcon class="h-5 w-5 mr-2" />
          拒绝申请
        </button>
      </div>
    </div>

    <div v-if="loading" class="text-center py-8">
      <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
      <p class="mt-2 text-gray-500">加载中...</p>
    </div>

    <div v-else-if="application" class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <!-- 基本信息 -->
      <div class="lg:col-span-2">
        <div class="bg-white rounded-xl shadow-lg p-6">
          <h3 class="text-lg font-semibold text-gray-800 mb-4">申请信息</h3>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-500">申请编号</label>
              <p class="mt-1 text-sm text-gray-900">#{{ application.id }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">申请状态</label>
              <span :class="['px-2 inline-flex text-xs leading-5 font-semibold rounded-full', getStatusClass(application.status)]">
                {{ getStatusText(application.status) }}
              </span>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">设备类别</label>
              <p class="mt-1 text-sm text-gray-900">{{ application.category }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">设备名称</label>
              <p class="mt-1 text-sm text-gray-900">{{ application.name }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">规格型号</label>
              <p class="mt-1 text-sm text-gray-900">{{ application.specification || '-' }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">申请数量</label>
              <p class="mt-1 text-sm text-gray-900">{{ application.quantity }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">预估单价</label>
              <p class="mt-1 text-sm text-gray-900">{{ application.unitPrice ? `¥${application.unitPrice}` : '-' }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">紧急程度</label>
              <span :class="['px-2 inline-flex text-xs leading-5 font-semibold rounded-full', getUrgencyClass(application.urgency)]">
                {{ getUrgencyText(application.urgency) }}
              </span>
            </div>
            <div class="md:col-span-2">
              <label class="block text-sm font-medium text-gray-500">申请理由</label>
              <p class="mt-1 text-sm text-gray-900">{{ application.reason }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 申请人和审批信息 -->
      <div>
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
          <h3 class="text-lg font-semibold text-gray-800 mb-4">申请人信息</h3>
          <div class="space-y-3">
            <div>
              <label class="block text-sm font-medium text-gray-500">申请人</label>
              <p class="mt-1 text-sm text-gray-900">{{ application.applicantName }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">所属实验室</label>
              <p class="mt-1 text-sm text-gray-900">{{ application.laboratoryName }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">申请时间</label>
              <p class="mt-1 text-sm text-gray-900">{{ application.createTime }}</p>
            </div>
          </div>
        </div>

        <!-- 审批信息 -->
        <div class="bg-white rounded-xl shadow-lg p-6" v-if="application.status !== 'PENDING'">
          <h3 class="text-lg font-semibold text-gray-800 mb-4">审批信息</h3>
          <div class="space-y-3">
            <div>
              <label class="block text-sm font-medium text-gray-500">审批人</label>
              <p class="mt-1 text-sm text-gray-900">{{ application.approverName || '-' }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">审批时间</label>
              <p class="mt-1 text-sm text-gray-900">{{ application.approvalTime || '-' }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">审批意见</label>
              <p class="mt-1 text-sm text-gray-900">{{ application.approvalComment || '-' }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div v-else class="text-center py-8">
      <p class="text-gray-500">申请信息不存在</p>
    </div>

    <!-- 批准对话框 -->
    <div v-if="showApprovalDialog" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
      <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="mt-3">
          <h3 class="text-lg font-medium text-gray-900 mb-4">批准申请</h3>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">审批意见</label>
            <textarea v-model="approvalComment" rows="3" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" placeholder="请输入审批意见"></textarea>
          </div>
          <div class="flex justify-end space-x-3">
            <button @click="cancelApproval" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400">取消</button>
            <button @click="confirmApproval" :disabled="approvalLoading" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50">
              {{ approvalLoading ? '处理中...' : '确认批准' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 拒绝对话框 -->
    <div v-if="showRejectDialog" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
      <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="mt-3">
          <h3 class="text-lg font-medium text-gray-900 mb-4">拒绝申请</h3>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">拒绝原因</label>
            <textarea v-model="rejectComment" rows="3" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" placeholder="请输入拒绝原因"></textarea>
          </div>
          <div class="flex justify-end space-x-3">
            <button @click="cancelReject" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400">取消</button>
            <button @click="confirmReject" :disabled="rejectLoading" class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 disabled:opacity-50">
              {{ rejectLoading ? '处理中...' : '确认拒绝' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import {
  ArrowLeftIcon,
  PencilIcon,
  CheckIcon,
  XMarkIcon,
} from '@heroicons/vue/24/outline'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const application = ref(null)
const showApprovalDialog = ref(false)
const showRejectDialog = ref(false)
const approvalLoading = ref(false)
const rejectLoading = ref(false)
const approvalComment = ref('')
const rejectComment = ref('')

// 获取申请详情
const loadApplicationDetail = async () => {
  try {
    loading.value = true
    const applicationId = route.params.id
    
    const response = await request.get(`/equipment-application/${applicationId}`)
    application.value = response.data
    
  } catch (error) {
    console.error('加载申请详情失败:', error)
    showMessage('加载申请详情失败', 'error')
  } finally {
    loading.value = false
  }
}

// 编辑申请
const editApplication = () => {
  router.push(`/equipment-application/form/${application.value.id}`)
}

// 批准申请
const approveApplication = () => {
  showApprovalDialog.value = true
  approvalComment.value = ''
}

// 拒绝申请
const rejectApplication = () => {
  showRejectDialog.value = true
  rejectComment.value = ''
}

// 取消批准
const cancelApproval = () => {
  showApprovalDialog.value = false
  approvalComment.value = ''
}

// 取消拒绝
const cancelReject = () => {
  showRejectDialog.value = false
  rejectComment.value = ''
}

// 确认批准
const confirmApproval = async () => {
  try {
    approvalLoading.value = true
    
    const requestData = {
      status: 'APPROVED',
      comment: approvalComment.value
    }
    
    await request.put(`/equipment-application/${application.value.id}/approve`, requestData)
    showMessage('申请已批准', 'success')
    
    showApprovalDialog.value = false
    loadApplicationDetail() // 重新加载数据
    
  } catch (error) {
    console.error('批准申请失败:', error)
    showMessage('批准申请失败', 'error')
  } finally {
    approvalLoading.value = false
  }
}

// 确认拒绝
const confirmReject = async () => {
  try {
    rejectLoading.value = true
    
    const requestData = {
      status: 'REJECTED',
      comment: rejectComment.value
    }
    
    await request.put(`/equipment-application/${application.value.id}/approve`, requestData)
    showMessage('申请已拒绝', 'success')
    
    showRejectDialog.value = false
    loadApplicationDetail() // 重新加载数据
    
  } catch (error) {
    console.error('拒绝申请失败:', error)
    showMessage('拒绝申请失败', 'error')
  } finally {
    rejectLoading.value = false
  }
}

// 获取状态样式
const getStatusClass = (status) => {
  const statusMap = {
    'PENDING': 'bg-yellow-100 text-yellow-800',
    'APPROVED': 'bg-green-100 text-green-800',
    'REJECTED': 'bg-red-100 text-red-800',
    'PURCHASED': 'bg-blue-100 text-blue-800'
  }
  return statusMap[status] || 'bg-gray-100 text-gray-800'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'PENDING': '待审批',
    'APPROVED': '已批准',
    'REJECTED': '已拒绝',
    'PURCHASED': '已购买'
  }
  return statusMap[status] || status
}

// 获取紧急程度样式
const getUrgencyClass = (urgency) => {
  const urgencyMap = {
    'LOW': 'bg-green-100 text-green-800',
    'MEDIUM': 'bg-yellow-100 text-yellow-800',
    'HIGH': 'bg-red-100 text-red-800'
  }
  return urgencyMap[urgency] || 'bg-gray-100 text-gray-800'
}

// 获取紧急程度文本
const getUrgencyText = (urgency) => {
  const urgencyMap = {
    'LOW': '低',
    'MEDIUM': '中',
    'HIGH': '高'
  }
  return urgencyMap[urgency] || urgency
}

// 检查是否有审批权限
const hasApprovalPermission = () => {
  const user = userStore.user
  return user && (user.role === 'ADMIN' || user.role === 'LEADER')
}

// 消息提示
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

onMounted(() => {
  loadApplicationDetail()
})
</script>
